package cn.drenal.capcap.service.impl;

import cn.drenal.capcap.entity.SysAdminRole;
import cn.drenal.capcap.entity.dto.AdminRoleDTO;
import cn.drenal.capcap.mapper.SysAdminRoleMapper;
import cn.drenal.capcap.service.SysAdminRoleService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户角色管理服务实现类
 */
@Service
@RequiredArgsConstructor
public class SysAdminRoleServiceImpl implements SysAdminRoleService {

    private final SysAdminRoleMapper sysAdminRoleMapper;

    /**
     * 分配用户角色
     *
     * @param adminRoleDTO 用户角色信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void assignAdminRole(AdminRoleDTO adminRoleDTO) {
        Long userId = adminRoleDTO.getUserId();
        List<Long> roleIds = adminRoleDTO.getRoleIds();
        
        // 删除用户现有角色
        sysAdminRoleMapper.delete(
                new LambdaQueryWrapper<SysAdminRole>()
                        .eq(SysAdminRole::getUserId, userId));
        
        // 如果角色列表为空，则不添加新角色
        if (roleIds == null || roleIds.isEmpty()) {
            return;
        }
        
        // 批量添加新角色
        List<SysAdminRole> adminRoles = roleIds.stream().map(roleId -> {
            SysAdminRole adminRole = new SysAdminRole();
            adminRole.setUserId(userId);
            adminRole.setRoleId(roleId);
            return adminRole;
        }).collect(Collectors.toList());
        
        adminRoles.forEach(sysAdminRoleMapper::insert);
    }

    /**
     * 获取用户角色ID列表
     *
     * @param userId 用户ID
     * @return 角色ID列表
     */
    @Override
    public List<Long> getAdminRoleIds(Long userId) {
        List<SysAdminRole> adminRoles = sysAdminRoleMapper.selectList(
                new LambdaQueryWrapper<SysAdminRole>()
                        .eq(SysAdminRole::getUserId, userId));
        
        if (adminRoles.isEmpty()) {
            return new ArrayList<>();
        }
        
        return adminRoles.stream()
                .map(SysAdminRole::getRoleId)
                .collect(Collectors.toList());
    }
}